import { DependencyContainer, Request, CoreError } from "@sker/core"
import { z } from "zod"
import { usePlugin } from '@sker/core'
const schema = z.object({
    resource: z.string(),
    variables: z.any()
});
export default async (injector: DependencyContainer) => {
    const req = injector.resolve(Request)
    const body = schema.parse(req.body)
    const res = await usePlugin('@sker/orm', async (ds) => {
        const registry = ds.manager.getRepository(body.resource)
        try {
            const res = await registry.save(body.variables)
            if (res) {
                return res;
            } else {
                return { success: false, message: '更新失败' }
            }
        } catch (e) {
            const message: string = (e as any).message
            if (message.startsWith('duplicate key value violates unique constraint')) {
                return { success: false, message: '唯一键冲突，数据已存在' }
            }
            return { success: false, message: message }
        }
    })
    return res;
}

export class InsertFailError extends CoreError<object> {
    constructor(data: any) {
        super(200, 'fail', data)
    }
}